#!/usr/bin/env node

import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 修复Java版本的函数
function fixJavaVersion() {
    console.log('🔧 Fixing Java version before run...');
    
    const filesToFix = [
        'android/app/capacitor.build.gradle',
        'android/capacitor-cordova-android-plugins/build.gradle'
    ];
    
    let fixedCount = 0;
    
    filesToFix.forEach(filePath => {
        const fullPath = path.join(__dirname, filePath);
        
        if (fs.existsSync(fullPath)) {
            let content = fs.readFileSync(fullPath, 'utf8');
            
            // 替换Java 21为Java 17
            const originalContent = content;
            content = content.replace(/JavaVersion\.VERSION_21/g, 'JavaVersion.VERSION_17');
            
            if (content !== originalContent) {
                fs.writeFileSync(fullPath, content);
                console.log(`✅ Fixed Java version in ${filePath}`);
                fixedCount++;
            }
        }
    });
    
    if (fixedCount > 0) {
        console.log(`🎉 Fixed Java version in ${fixedCount} file(s)`);
    } else {
        console.log('✅ All Java versions are already correct');
    }
}

// 运行Capacitor Android
function runAndroid() {
    try {
        console.log('🚀 Running Android app...');
        
        // 在运行前再次修复Java版本
        fixJavaVersion();
        
        // 运行Android应用
        execSync('npx cap run android', { stdio: 'inherit' });
    } catch (error) {
        console.error('❌ Failed to run Android app:', error.message);
        
        // 如果失败，再次尝试修复Java版本
        console.log('🔧 Attempting to fix Java version after failure...');
        fixJavaVersion();
        
        process.exit(1);
    }
}

// 主函数
function main() {
    console.log('🎯 Starting Android run with Java version fix...');
    
    // 1. 修复Java版本
    fixJavaVersion();
    
    // 2. 运行Android应用
    runAndroid();
}

// 运行主函数
main();
